<?php
include("DB_SQLLIB.php");
  //$_SESSION['db'] = $db;
  $db = connect_database("bbmingle.db.4975972.hostedresource.com", "bbmingle", "bbmingle", "Mingle2012");
  $_SESSION['db'] = $db; 
  
if(isset($_POST['action']))
{   
    if($_POST['action']== "register")
    {
        if(!pinExists($_POST['pin']))
        {
            registerDevice("BB", $_POST['pin'], $_POST['email'], md5($_POST['password']), $_POST['screenName'], $_POST['dob'], $_POST['status'], $_POST['aboutYou'],$_POST['gender'], $_POST['city'], $_POST['province'], $_POST['country'], $_POST['searchable'] ); 
            if(strlen(findProfileFromPin($_POST['pin'])) > 5)
            {
                if(isset($_FILES['upload_dp']))
                {            
                    $blob = file_get_contents($_FILES['upload_dp']['tmp_name']);
                    $blob = mysql_real_escape_string($blob);
                    $sql = "UPDATE PROFILE SET dp='$blob' where pinID=".getPinID($_POST['pin']);
                    exec_sql($_SESSION['db'], $sql );
                }
                echo "registration successful";
            }else
            {
                echo "registration failed";
            }
        }       
    }elseif($_POST['action']== "login")
    {
        $email = strtolower($_POST['email']);
        $pass = md5($_POST['password']);
        $pin = $_POST['pin'];   
        $sql = "SELECT pinID from PIN where (email='$email' OR pin='$pin') AND password='$pass'"; 
        $pid = get_a_value($_SESSION['db'], $sql);
        if($pid >= 0)
            echo "login successful";
        else
            echo "login failed";
    }elseif($_POST['action']== "findprofile")
    {
        echo findProfileFromPin($_POST['pin']);    
    }elseif($_POST['action'] == "listfriends")
    {
        $sql = "SELECT friendpinid from FRIENDS where mypinid=".getPinID($_POST['pin']);
        $result = get_query_list($_SESSION['db'], $sql);
        $xml = "<friends>\n";
        foreach($result as $pinid)
        {
            $xml .= "<pin>".getPin($pinid)."</pin>\n";
        }
        $xml.= "</friends>";
    }elseif($_POST['action'] == "emailexists")
    {
        if(getPinIDFromEmail($_POST['email']) >= 0 )
        {
            echo "YES";
        }else
        {
            echo "NO";
        }
    }
}elseif(isset($_FILES['upload_dp']))
{
    $blob = file_get_contents($_FILES['upload_dp']['tmp_name']);
    $sql = "UPDATE PROFILE SET dp='".$blob."' where pinID=".getPinID($_POST['pin']);
    exec_sql($_SESSION['db'], $sql );
}

function findProfileFromPin($pin)
{
    $from = " FROM PIN P, LOCATION L, PROFILE PR";
    $where = " WHERE P.pin='".$pin."' AND L.pinID=P.pinID AND PR.pinID = P.pinID ";
    $sql = "SELECT P.pinID, P.pin, PR.screenname, PR.status, PR.about, PR.gender, PR.dob, PR.searcheable, L.city, L.province, L.country".$from.$where;
    $rtn = get_query_row($_SESSION['db'], $sql);
    
    //echo $sql;
   $xml = "";
   if(count($rtn) > 0)
    {    
        $xml = "<data>\n";
        $xml .= "<row>\n";
    
        foreach($rtn as $key => $val)
        {
            $xml .= "<$key>" . $val. "</$key>\n";
        }
    
        $xml .= "</row>\n";
        $xml .="</data>\n";
    }
        return $xml;
}

/**
* By Default, $devive has been set to BB but in the future, change to device type
* 
* @param mixed $device
* @param mixed $pin
* @param mixed $email
* @param mixed $screenname
* @param mixed $dob
* @param mixed $status
* @param mixed $aboutMe
* @param mixed $gender
* @param mixed $city
* @param mixed $province
* @param mixed $country
* @param mixed $searchable
*/
  function registerDevice($device = "BB", $pin, $email, $pass, $screenname, $dob, $status, $aboutMe, $gender, $city, $province, $country, $searchable)
  {
      
      if(!pinExists($pin))
      {
        //Register pin and device = BB
        $sql = "INSERT INTO PIN(pin, email, password, device) VALUES('".$pin."','".$email."','".$pass."','".$device."')";
        exec_sql($_SESSION['db'], $sql);
        $pinID = getPinID($pin);
    //Register location with the given pinID
        $sql = "INSERT INTO LOCATION(pinID, country, province, city) VALUES($pinID, '".$country."', '".$province."', '".$city."')";
        exec_sql($_SESSION['db'], $sql);
        $locid = get_a_value($_SESSION['db'], "SELECT locationID from LOCATION where pinID=".intval($pinID));
    //Register profile with PINID, LOCATION ID,    
        $sql = "INSERT INTO PROFILE(pinID, locationID,screenname,status,about,gender,dob,searcheable) VALUES($pinID, $locid, '".$screenname."', '".$status."', '".$aboutMe."', '".$gender."', '". $dob."', '". $searchable."')";
        exec_sql($_SESSION['db'], $sql);
       // $profileid = get_a_value($_SESSION['db'], "SELECT locationID from LOCATION where pinID=".intval($pinID));
      }
     
  }
  
  /**
  * @desc Checks if the pin parsed exists in the DB
  */
  function pinExists($pin)
  {
    $sql = "SELECT pinID from PIN where pin='$pin'";
    $result = -1;
    $result = get_a_value($_SESSION['db'], $sql);
    if($result > 0)
    {
        return true;
    }
    return false;
  }
  /**
  * @desc Returns the pinID
  */
  function getPinID($pin)
  {
    $pid = get_a_value($_SESSION['db'], "SELECT pinID from PIN where pin='$pin'");
    return $pid;
  }
  
  function getPin($pinID)
  {
    $pin = get_a_value($_SESSION['db'], "SELECT pin from PIN where pinID=".$pinID);
    return $pin;
  }
  
  function getPinIDFromEmail($email)
  {
    $pid = get_a_value($_SESSION['db'], "SELECT pinID from PIN where email='$email'");
    return $pid;
  }
?>
